package com.zzw.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzw.bean.Product;
import com.zzw.bean.Shipment;
import com.zzw.bean.ShipmentItem;
import com.zzw.dao.ShipmentMapper;
import com.zzw.service.OrderService;
import com.zzw.service.ProductService;
import com.zzw.service.ShipmentService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShipmentServiceImpl implements ShipmentService {

   /* @Autowired
    private ShipmentMapper shipmentMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public int createShipment(Shipment shipment) {
        // 设置初始状态为待发货
        shipment.setStatus(0);
        Date now = new Date();
        shipment.setCreateTime(now);

        // 如果没有发货单号，则生成一个
        if (shipment.getShipmentNo() == null || shipment.getShipmentNo().isEmpty()) {
            shipment.setShipmentNo(generateShipmentNo());
        }

        // 插入发货单
        shipmentMapper.insertShipment(shipment);

        // 设置发货明细的shipmentId
        for (ShipmentItem item : shipment.getShipmentItems()) {
            item.setShipmentId(shipment.getId());
            item.setCreateTime(now);

            // 从商品表获取最新的商品信息
            if (item.getProductId() != null) {
                Product product = productService.getProductById(item.getProductId());
                if (product != null) {
                    item.setProductName(product.getProductName());
                }
            }
        }

        // 批量插入发货明细
        shipmentMapper.batchInsertShipmentItems(shipment.getShipmentItems());

        return shipment.getId();
    }

    @Override
    @Transactional
    public int confirmShipment(Integer id) {
        // 获取发货单信息
        Shipment shipment = shipmentMapper.selectShipmentDetailById(id);
        if (shipment == null) {
            return 0;
        }

        // 检查发货数量是否超过订单数量
        for (ShipmentItem item : shipment.getShipmentItems()) {
            // 获取该订单项当前已发货数量
            int currentShippedQuantity = orderService.getOrderItemById(item.getOrderItemId()).getShippedQuantity();
            // 获取该订单项总数量
            int totalQuantity = orderService.getOrderItemById(item.getOrderItemId()).getQuantity();

            // 检查本次发货后是否会超过总订购数量
            if (currentShippedQuantity + item.getQuantity() > totalQuantity) {
                throw new RuntimeException("商品已发货数量将超过订购数量，无法继续发货");
            }
        }

        Date now = new Date();

        // 更新发货单状态为已发货
        int result = shipmentMapper.updateShipmentStatus(id, 1, now);

        // 更新订单项的已发货数量和订单的发货状态
        if (result > 0 && shipment.getShipmentItems() != null && !shipment.getShipmentItems().isEmpty()) {
            // 更新每个订单项的已发货数量
            for (ShipmentItem item : shipment.getShipmentItems()) {
                Integer orderItemId = item.getOrderItemId();
                Integer quantity = item.getQuantity();//每个发货明细数量

                if (orderItemId != null && quantity != null) {
                    // 获取当前已发货数量
                    int currentShippedQuantity = orderService.getOrderItemById(orderItemId).getShippedQuantity();
                    // 计算新的已发货数量 = 当前已发货数量 + 本次发货数量
                    int newShippedQuantity = currentShippedQuantity + quantity;

                    // 更新订单项的已发货数量
                    orderService.updateOrderItemShippedQuantity(orderItemId, newShippedQuantity);
                }
            }

            // 计算并更新订单总的已发货数量
            updateOrderTotalShippedQuantity(shipment.getOrderId());
        }

        // 更新订单状态为已发货
        orderService.updateOrderToShipped(shipment.getOrderId());

        return result;
    }

    *//**
     * 更新订单总已发货数量
     * @param orderId 订单ID
     *//*
    private void updateOrderTotalShippedQuantity(Integer orderId) {
        // 获取订单所有项的已发货数量之和
        int totalShippedQuantity = shipmentMapper.sumOrderItemsShippedQuantity(orderId);

        // 更新订单总发货数量
        orderService.updateOrderShippedQuantity(orderId, totalShippedQuantity);
    }

    @Override
    public Shipment getShipmentById(Integer id) {
        return shipmentMapper.selectShipmentById(id);
    }

    @Override
    public Shipment getShipmentByOrderId(Integer orderId) {
        return shipmentMapper.selectShipmentByOrderId(orderId);
    }

    @Override
    public Shipment getShipmentDetailById(Integer id) {
        return shipmentMapper.selectShipmentDetailById(id);
    }

    @Override
    public PageInfo<Shipment> getShipmentList(Shipment shipment, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Shipment> shipments = shipmentMapper.selectShipmentList(shipment);
        return new PageInfo<>(shipments);
    }

    @Override
    public String generateShipmentNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String timeMillis = String.valueOf(System.currentTimeMillis()).substring(9);
        return "SHP" + dateStr + timeMillis;
    }

    @Override
    public List<Shipment> getShipmentsByOrderId(Integer orderId) {
        return shipmentMapper.selectShipmentsByOrderId(orderId);
    }

    @Override
    public int countShipmentsByOrderId(Integer orderId) {
        return shipmentMapper.countShipmentsByOrderId(orderId);
    }

    @Override
    public Map<Integer, Integer> getShippedItemsByOrderId(Integer orderId) {
        // 获取订单所有发货明细
        List<ShipmentItem> shipmentItems = shipmentMapper.selectShippedItemsByOrderId(orderId);

        Map<Integer, Integer> shippedItems = new HashMap<>();
        if (shipmentItems != null && !shipmentItems.isEmpty()) {
            // 按订单项ID聚合已发货数量
            for (ShipmentItem item : shipmentItems) {
                Integer orderItemId = item.getOrderItemId();
                Integer quantity = item.getQuantity();

                if (orderItemId != null && quantity != null) {
                    // 累加已发货数量
                    shippedItems.put(orderItemId, shippedItems.getOrDefault(orderItemId, 0) + quantity);
                }
            }
        }

        return shippedItems;
    }

    *//**
     * 获取订单中已确认的发货单明细（排除当前正在确认的发货单）
     * @param orderId 订单ID
     * @param currentShipmentId 当前正在确认的发货单ID
     * @return 已确认发货数量映射表
     *//*
    @Deprecated
    public Map<Integer, Integer> getConfirmedShippedItemsByOrderId(Integer orderId, Integer currentShipmentId) {
        // 获取订单所有已确认的发货明细
        List<ShipmentItem> shipmentItems = shipmentMapper.selectConfirmedShippedItemsByOrderId(orderId, currentShipmentId);

        Map<Integer, Integer> shippedItems = new HashMap<>();
        if (shipmentItems != null && !shipmentItems.isEmpty()) {
            // 按订单项ID聚合已发货数量
            for (ShipmentItem item : shipmentItems) {
                Integer orderItemId = item.getOrderItemId();
                Integer quantity = item.getQuantity();

                if (orderItemId != null && quantity != null) {
                    // 累加已发货数量
                    shippedItems.put(orderItemId, shippedItems.getOrDefault(orderItemId, 0) + quantity);
                }
            }
        }

        return shippedItems;
    }

    @Override
    public boolean existsByOrderId(Integer orderId) {
        return countShipmentsByOrderId(orderId) > 0;
    }*/
}
